package com.aiyige.page.message;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventNewMessageChanged;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.model.message.entity.Message;
import com.aiyige.model.message.view.MessageSummary;
import com.aiyige.page.my.message.util.MessageUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class MessagePage extends BaseFragment {

    @BindView(R.id.sysMessageIv)
    ImageView sysMessageIv;
    @BindView(R.id.sysMessageUnReadNumTv)
    TextView sysMessageUnReadNumTv;
    @BindView(R.id.sysMessageContentTv)
    TextView sysMessageContentTv;
    @BindView(R.id.sysMessageLayout)
    RelativeLayout sysMessageLayout;
    @BindView(R.id.likeMessageIv)
    ImageView likeMessageIv;
    @BindView(R.id.likeMessageUnReadNumTv)
    TextView likeMessageUnReadNumTv;
    @BindView(R.id.likeMessageContentTv)
    TextView likeMessageContentTv;
    @BindView(R.id.likeMessageLayout)
    RelativeLayout likeMessageLayout;
    @BindView(R.id.collectionMessageIv)
    ImageView collectionMessageIv;
    @BindView(R.id.collectionMessageUnReadNumTv)
    TextView collectionMessageUnReadNumTv;
    @BindView(R.id.collectionMessageContentTv)
    TextView collectionMessageContentTv;
    @BindView(R.id.collectionMessageLayout)
    RelativeLayout collectionMessageLayout;
    @BindView(R.id.commentMessageIv)
    ImageView commentMessageIv;
    @BindView(R.id.commentMessageUnReadNumTv)
    TextView commentMessageUnReadNumTv;
    @BindView(R.id.commentMessageContentTv)
    TextView commentMessageContentTv;
    @BindView(R.id.commentMessageLayout)
    RelativeLayout commentMessageLayout;
    @BindView(R.id.orderMessageIv)
    ImageView orderMessageIv;
    @BindView(R.id.orderMessageUnReadNumTv)
    TextView orderMessageUnReadNumTv;
    @BindView(R.id.orderMessageContentTv)
    TextView orderMessageContentTv;
    @BindView(R.id.orderMessageLayout)
    RelativeLayout orderMessageLayout;
    Unbinder unbinder;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    Handler mainHandler;

    public MessagePage() {
        setAutoRegisterEventBus(true);
    }

    public static MessagePage newInstance() {
        MessagePage fragment = new MessagePage();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_message, container, false);
        unbinder = ButterKnife.bind(this, view);
        mainHandler = new Handler(Looper.getMainLooper());
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData();
            }
        });
        return view;
    }


    @Override
    protected void initData() {
        requestData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        List<MessageSummary> messageSummaryList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().messageSummary().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                messageSummaryList.addAll(JSON.parseArray(json, MessageSummary.class));
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            swipeRefreshLayout.setRefreshing(false);
            if (o instanceof Exception) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                        .build());
                ToastX.show(((Exception) o).getMessage());
            } else {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                        .build());
                for (MessageSummary messageSummary : messageSummaryList) {
                    switch (messageSummary.getType()) {
                        case Message.TYPE_SYSTEM:
                            if (messageSummary.getCount() > 0) {
                                sysMessageUnReadNumTv.setVisibility(View.VISIBLE);
                                sysMessageUnReadNumTv.setText(MessageUtil.formatUnReadMessageNum(messageSummary.getCount()));
                            } else {
                                sysMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                            }
                            sysMessageContentTv.setText(messageSummary.getMessage());
                            break;
                        case Message.TYPE_FAVOURITE:
                            if (messageSummary.getCount() > 0) {
                                collectionMessageUnReadNumTv.setVisibility(View.VISIBLE);
                                collectionMessageUnReadNumTv.setText(MessageUtil.formatUnReadMessageNum(messageSummary.getCount()));
                            } else {
                                collectionMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                            }
                            collectionMessageContentTv.setText(messageSummary.getMessage());
                            break;
                        case Message.TYPE_ORDER:
                            if (messageSummary.getCount() > 0) {
                                orderMessageUnReadNumTv.setVisibility(View.VISIBLE);
                                orderMessageUnReadNumTv.setText(MessageUtil.formatUnReadMessageNum(messageSummary.getCount()));
                            } else {
                                orderMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                            }
                            orderMessageContentTv.setText(messageSummary.getMessage());
                            break;
                        case Message.TYPE_PRAISE:
                            if (messageSummary.getCount() > 0) {
                                likeMessageUnReadNumTv.setVisibility(View.VISIBLE);
                                likeMessageUnReadNumTv.setText(MessageUtil.formatUnReadMessageNum(messageSummary.getCount()));
                            } else {
                                likeMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                            }
                            likeMessageContentTv.setText(messageSummary.getMessage());
                            break;
                        case Message.TYPE_COMMENT:
                            if (messageSummary.getCount() > 0) {
                                commentMessageUnReadNumTv.setVisibility(View.VISIBLE);
                                commentMessageUnReadNumTv.setText(MessageUtil.formatUnReadMessageNum(messageSummary.getCount()));
                            } else {
                                commentMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                            }
                            commentMessageContentTv.setText(messageSummary.getMessage());
                            break;
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReceiveNewMessage(EventNewMessageChanged event) {
        if (event.isDontRequestData()) {
            clearUnRead();
            return;
        }
        if (isFragmentVisible()) {
            requestData();
        } else {
            setForceLoad(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (isFragmentVisible()
                && event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH) {
            swipeRefreshLayout.setRefreshing(true);
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestData();
                }
            }, 1000);
        }
    }

    public void clearUnRead() {
        sysMessageUnReadNumTv.setVisibility(View.INVISIBLE);
        sysMessageContentTv.setText("");

        likeMessageUnReadNumTv.setVisibility(View.INVISIBLE);
        likeMessageContentTv.setText("");

        collectionMessageUnReadNumTv.setVisibility(View.INVISIBLE);
        collectionMessageContentTv.setText("");

        commentMessageUnReadNumTv.setVisibility(View.INVISIBLE);
        commentMessageContentTv.setText("");

        orderMessageUnReadNumTv.setVisibility(View.INVISIBLE);
        orderMessageContentTv.setText("");
    }

    @OnClick({R.id.sysMessageLayout, R.id.likeMessageLayout, R.id.collectionMessageLayout, R.id.commentMessageLayout, R.id.orderMessageLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sysMessageLayout:
                sysMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                sysMessageContentTv.setText("");
                ARouter.getInstance().build(ARouterConfig.SysMessagePage).navigation();
                break;
            case R.id.likeMessageLayout:
                likeMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                likeMessageContentTv.setText("");
                ARouter.getInstance().build(ARouterConfig.InteractMessagePage).navigation();
                break;
            case R.id.collectionMessageLayout:
                collectionMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                collectionMessageContentTv.setText("");
                ARouter.getInstance().build(ARouterConfig.CollectionMessagePage).navigation();
                break;
            case R.id.commentMessageLayout:
                commentMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                commentMessageContentTv.setText("");
                ARouter.getInstance().build(ARouterConfig.CommentMessagePage).navigation();
                break;
            case R.id.orderMessageLayout:
                orderMessageUnReadNumTv.setVisibility(View.INVISIBLE);
                orderMessageContentTv.setText("");
                ARouter.getInstance().build(ARouterConfig.OrderMessagePage).navigation();
                break;
        }
    }
}
